package com.aratana.util;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;

import org.apache.log4j.Logger;

public final class ResourceManager {

	private static final Logger logger = Logger.getLogger(ResourceManager.class);

	private static final Map<String, ResourceBundle> bundles = new HashMap<String, ResourceBundle>();

	private ResourceManager() {
	}

	public static final String getString(String context, String key) {
		boolean us = false;
		try {
			ResourceBundle bundle = bundles.get(context);
			if (bundle == null) {
				try {
					bundle = ResourceBundle.getBundle(context);
				} catch (Exception e) {
					logger.warn("Cannot locate resource '" + context + "' for locale " + Locale.getDefault());
					bundle = ResourceBundle.getBundle(context, Locale.US);
					us = true;
				}
				bundles.put(context, bundle);
			}

			return bundle.getString(key);
		} catch (Exception e) {
			if (!us) {
				try {
					String resource = ResourceBundle.getBundle(context, Locale.US).getString(key);
					logger.warn("Using ${" + context + "." + key + "} in " + Locale.US + " locale.");
					return resource;
				} catch (Exception ex) {
				}
			}
			logger.error("Cannot found string ${" + context + "." + key + "}.");
			return "${" + context + "." + key + "}";
		}
	}

	public static final void unloadContext(String context) {
		bundles.remove(context);
	}

	public  static final void reloadContext(String context) {
		unloadContext(context);
		ResourceBundle bundle = ResourceBundle.getBundle(context);
		bundles.put(context, bundle);
	}
}
